# coding: utf-8

import urllib

from django.http import HttpResponse, HttpResponseRedirect
from django import http
from django.template import Context, loader
from django.core.urlresolvers import reverse

from douban.service import DoubanService
from douban.client import OAuthClient
import douban
import atom

API_KEY='046a0792404735c00d3e16b6c0d5a140'
SECRET='4be055fdab5fe0d5'

def index(request):
    
    service = DoubanService(api_key=API_KEY,secret=SECRET)
    
    islogin = is_logined(request)
    
    template = loader.get_template('douyou/templates/index.html')
    context = Context({
        'islogin': islogin,
    })
    
    if islogin:
        key, secret, uid = request.session['oauth_access_token']
        service.ProgrammaticLogin(key, secret)
        people = service.GetPeople(urllib.quote('/people/@me'))
        
        context['people'] = people
    
    return HttpResponse(template.render(context))

def is_logined(request):
    
    if 'oauth_access_token' in request.session:
        return True
    else:
        return False
    
def broadcast(request):

    if is_logined(request):
        
        content = request.POST.get('content')
        service = DoubanService(api_key=API_KEY,secret=SECRET)
        
        key, secret, uid = request.session['oauth_access_token']
        service.ProgrammaticLogin(token_key=key, token_secret=secret)
        
        entry = douban.BroadcastingEntry()
        entry.content = atom.Content(text=content)
        entry = service.AddBroadcasting('/miniblog/saying', entry)
    
    return HttpResponseRedirect('/')

def findpeople1(request):
    """搜集当前用户的信息"""
    
    if is_logined(request):
        key, secret, uid = request.session['oauth_access_token']
        service = DoubanService(api_key=API_KEY,secret=SECRET)
        service.ProgrammaticLogin(token_key=key, token_secret=secret)
        
        me = service.GetPeople('/people/@me')
        
    
    return HttpResponseRedirect('/')

def findpeople2(request):
    """搜索匹配信息"""
    
    
    return HttpResponseRedirect('/')

def others(request):
    
    # 豆瓣是根据评星在4星以上决定，是否是共同爱好的
    
    # 想法：1.根据好友的好友找。2.从头遍历所有人找。3.随机算法，启发算法
    
    # 两个人怎么才算兴趣相同，书，影，音品味相同还是分开，
    # 还有小组，评论，活动，推荐等因素，想一个公式算一个加权平均。
    
    
    
    template = loader.get_template('douyou/templates/others.html')
    context = Context({
       
    })
    
    return HttpResponse(template.render(context))

def me(request):
    
    if not is_logined(request):
        return HttpResponseRedirect('/')
    
    key, secret, uid = request.session['oauth_access_token']
    service = DoubanService(api_key=API_KEY,secret=SECRET)
    service.ProgrammaticLogin(token_key=key, token_secret=secret)
    
    try:
        meurl = urllib.quote('/people/@me')
#        meurl = '/people/%s' % uid
        me = service.GetPeople(meurl)
#        mstr = '/people/@me'
#        service.GetPeople(mstr)
        books = service.GetCollectionFeed('/people/%s/collection?cat=book' % uid)
        movies = service.GetCollectionFeed('/people/%s/collection?cat=movie' % uid)
        #service.ge
    except:
        return http.HttpResponseServerError()
        
    
    template = loader.get_template('douyou/templates/me.html')
    context = Context({
       'me': me,
       'books': books,
       'movies': movies,
    })
    
    return HttpResponse(template.render(context))

def login(request):
    
    oauth = OAuthClient(key=API_KEY, secret=SECRET)
    key, secret = oauth.get_request_token()
    request.session['oauth_request_token'] = key, secret
    callback_url = 'http://%s/login_check' % request.META['HTTP_HOST']
    auth_url = oauth.get_authorization_url(key, secret, callback_url)
    
    return HttpResponseRedirect(auth_url)

def login_check(request):
    
    oauth = OAuthClient(key=API_KEY, secret=SECRET)
    key, secret = request.session['oauth_request_token']
    key, secret, uid = oauth.get_access_token(key, secret)
    del request.session['oauth_request_token']
    
    request.session['oauth_access_token'] = key, secret, uid
    oauth.login(key, secret)
    
    return HttpResponseRedirect('/')
    
def logout(request):
    
    del request.session['oauth_access_token']
    
    return HttpResponseRedirect('/')
    
def get_referer_url(request):
    """获得请求页的url"""
    
    referer_url = request.META.get('HTTP_REFERER', '/')
    host = request.META['HTTP_HOST']
    if referer_url.startswith('http') and host not in referer_url:
        referer_url = '/' # 避免外站直接跳到登录页而发生跳转错误
    return referer_url